<template>
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
        <div class="modal-content box-radius" @click.stop>
          <div class="modal-header">
            <h3>{{
                isForgotPassword
                  ? '找回密码'
                  : (isLogin ? '登录' : '注册')
              }}</h3>
            <button class="close-btn" @click="handleClose">
              <i class="fas fa-times"></i>
            </button>
          </div>

          <div class="modal-body">
            <!-- 切换登录/注册的标签 -->
            <div v-if="!isForgotPassword" class="auth-tabs">
              <button
                :class="['tab-btn', { active: isLogin }]"
                @click="switchMode(true)"
              >
                登录
              </button>
              <button
                :class="['tab-btn', { active: !isLogin }]"
                @click="switchMode(false)"
              >
                注册
              </button>
            </div>

            <Transition name="slide-fade" mode="out-in">
              <form :key="formKey" class="login-form" @submit.prevent="handleSubmit" novalidate>
                <!-- 忘记密码表单 -->
                <template v-if="isForgotPassword">
                  <div class="form-item">
                    <input
                      v-model="formData.email"
                      type="email"
                      placeholder="请输入注册邮箱"
                      required
                      :class="{ error: errors.email }"
                      @blur="validateEmail"
                    >
                    <span v-if="errors.email" class="error-message">
                      <i class="fas fa-exclamation-circle"></i>
                      {{ errors.email }}
                    </span>
                  </div>
                  <div class="form-tips">
                    <p>重置密码链接将发送到您的邮箱</p>
                  </div>
                  <button type="submit" class="submit-btn" :disabled="loading">
                    {{ loading ? '发送中...' : '发送重置链接' }}
                  </button>
                  <div class="back-to-login">
                    <button type="button" class="text-btn" @click="backToLogin">
                      返回登录
                    </button>
                  </div>
                </template>
                <!-- 登录/注册表单 -->
                <template v-else>
                  <div class="form-item">
                    <input
                      v-model="formData.email"
                      type="email"
                      placeholder="邮箱"
                      required
                      :class="{ error: errors.email }"
                      @blur="validateEmail"
                    >
                    <span v-if="errors.email" class="error-message">
                      <i class="fas fa-exclamation-circle"></i>
                      {{ errors.email }}
                    </span>
                  </div>

                  <!-- 注册时显示的额外字段 -->
                  <template v-if="!isLogin">
                    <div class="form-item">
                      <input
                        v-model="formData.nickname"
                        type="text"
                        placeholder="昵称"
                        required
                        :class="{ error: errors.nickname }"
                        @blur="validateNickname"
                      >
                      <span v-if="errors.nickname" class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        {{ errors.nickname }}
                      </span>
                    </div>
                    <div class="form-item">
                      <div class="password-input-wrapper">
                        <input
                          v-model="formData.password"
                          :type="showPassword1 ? 'text' : 'password'"
                          placeholder="密码"
                          required
                          :class="{ error: errors.password }"
                          @blur="validatePassword"
                          @input="checkPasswordStrength"
                        >
                        <!-- 自定义密码显示/隐藏按钮 -->
                        <button
                          type="button"
                          class="toggle-password"
                          @click="togglePassword(true)"
                          :title="showPassword1 ? '隐藏密码' : '显示密码'"
                        >
                          <PhEyeSlash v-if="showPassword1" :size="16" />
                          <PhEye v-else :size="16"/>
                        </button>
                        <!-- 密码强度指示器 -->
                        <div v-if="passwordStrength.show" class="password-strength">
                          <div class="strength-bars">
                            <span
                              v-for="n in 3"
                              :key="n"
                              :class="['bar', { active: passwordStrength.level >= n }]"
                              :style="{ '--strength-color': passwordStrength.color }"
                            ></span>
                          </div>
                          <span class="strength-text" :style="{ color: passwordStrength.color }">
                            {{ passwordStrength.text }}
                          </span>
                        </div>
                      </div>
                      <span v-if="errors.password" class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        {{ errors.password }}
                      </span>
                    </div>
                    <div class="form-item">
                      <div class="password-input-wrapper">
                        <input
                          v-model="formData.confirmPassword"
                          :type="showPassword2 ? 'text' : 'password'"
                          placeholder="确认密码"
                          required
                          :class="{ error: errors.confirmPassword }"
                          @blur="validateConfirmPassword"
                        >
                        <button
                          type="button"
                          class="toggle-password"
                          @click="togglePassword(false)"
                          :title="showPassword2 ? '隐藏密码' : '显示密码'"
                        >
                          <PhEyeSlash v-if="showPassword2" :size="16" />
                          <PhEye v-else :size="16"/>
                        </button>
                      </div>
                      <span v-if="errors.confirmPassword" class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        {{ errors.confirmPassword }}
                      </span>
                    </div>
                  </template>
                  <!-- 登录时显示的密码字段 -->
                  <template v-else>
                    <div class="form-item">
                      <div class="password-input-wrapper">
                        <input
                          v-model="formData.password"
                          :type="showPassword1 ? 'text' : 'password'"
                          placeholder="密码"
                          required
                          :class="{ error: errors.password }"
                          @blur="validatePassword"
                          @input="checkPasswordStrength"
                        >
                        <button
                          type="button"
                          class="toggle-password"
                          @click="togglePassword(true)"
                          :title="showPassword1 ? '隐藏密码' : '显示密码'"
                        >
                          <PhEyeSlash v-if="showPassword1" :size="16" />
                          <PhEye v-else :size="16"/>
                        </button>
                      </div>
                      <span v-if="errors.password" class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        {{ errors.password }}
                      </span>
                    </div>
                    <div class="forgot-password">
                      <button type="button" class="text-btn" @click="showForgotPassword">
                        忘记密码？
                      </button>
                    </div>
                  </template>

                  <div class="form-tips">
                    <p>{{ isLogin ? '登录后即可发表评论' : '注册信息仅用于评论显示' }}</p>
                  </div>

                  <button type="submit" class="submit-btn" :disabled="loading">
                    {{ loading ? (isLogin ? '登录中...' : '注册中...') : (isLogin ? '登录' : '注册') }}
                  </button>

                  <!-- 社交账号登录 -->
                  <div class="social-login">
                    <div class="divider">
                      <span>社交账号登录</span>
                    </div>
                    <div class="social-buttons">
                      <button type="button" class="social-btn qq" @click="handleSocialLogin('qq')">
                        <i class="fab fa-qq"></i>
                      </button>
                      <button type="button" class="social-btn wechat" @click="handleSocialLogin('wechat')">
                        <i class="fab fa-weixin"></i>
                      </button>
                      <button type="button" class="social-btn gitee" @click="handleSocialLogin('gitee')">
                        <i class="fab fa-git-alt"></i>
                      </button>
                    </div>
                  </div>
                </template>
              </form>
            </Transition>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { PhEye, PhEyeSlash } from '@phosphor-icons/vue';
import Message from '@/components/message';
import { useUserStore } from '@/stores';
import { sendResetPasswordEmail } from '@/api/portal';

// 类型定义
interface FormData {
  email: string;
  nickname: string;
  password: string;
  confirmPassword: string;
}

interface FormErrors {
  [key: string]: string;
}

interface PasswordStrength {
  show: boolean;
  level: number;
  text: string;
  color: string;
}

const props = defineProps<{
  visible: boolean
}>();

const emit = defineEmits(['update:visible', 'success']);

const userStore = useUserStore();
const isLogin = ref(true);
const isForgotPassword = ref(false);
const loading = ref(false);
const showPassword1 = ref(false);
const showPassword2 = ref(false);

// 用于触发表单切换动画
const formKey = computed(() => {
  return `${isLogin.value}-${isForgotPassword.value}`;
});

const formData = reactive<FormData>({
  email: '',
  nickname: '',
  password: '',
  confirmPassword: ''
});

const errors = reactive<FormErrors>({
  email: '',
  nickname: '',
  password: '',
  confirmPassword: ''
});

// 密码强度相关的响应式数据
const passwordStrength = reactive<PasswordStrength>({
  show: false,
  level: 0, // 0-3
  text: '',
  color: ''
});

// 密码强度检测函数
const checkPasswordStrength = () => {
  const password = formData.password;
  passwordStrength.show = password.length > 0;

  if (password.length === 0) {
    passwordStrength.level = 0;
    passwordStrength.text = '';
    return;
  }

  let level = 0;
  if (password.length >= 6) level++;
  if (/[A-Z]/.test(password) && /[a-z]/.test(password)) level++;
  if (/[0-9]/.test(password)) level++;
  if (/[^A-Za-z0-9]/.test(password)) level++;

  passwordStrength.level = Math.min(level, 3);

  switch (passwordStrength.level) {
  case 1:
    passwordStrength.text = '弱';
    passwordStrength.color = '#ef4444';
    break;
  case 2:
    passwordStrength.text = '中';
    passwordStrength.color = '#f59e0b';
    break;
  case 3:
    passwordStrength.text = '强';
    passwordStrength.color = '#10b981';
    break;
  default:
    passwordStrength.text = '弱';
    passwordStrength.color = '#ef4444';
  }
};

const togglePassword = (type: boolean) => {
  if(type) {
    showPassword1.value = !showPassword1.value;
  } else {
    showPassword2.value = !showPassword2.value;
  }
};

const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!formData.email) {
    errors.email = '请输入邮箱地址';
  } else if (!emailRegex.test(formData.email)) {
    errors.email = '请输入有效的邮箱地址';
  } else {
    errors.email = '';
  }
};

const validateNickname = () => {
  if (!formData.nickname) {
    errors.nickname = '请输入昵称';
  } else if (formData.nickname.length < 2) {
    errors.nickname = '昵称至少需要2个字符';
  } else {
    errors.nickname = '';
  }
};

const validatePassword = () => {
  if (!formData.password) {
    errors.password = '请输入密码';
  } else if (formData.password.length < 6) {
    errors.password = '密码至少需要6个字符';
  } else if (!isLogin.value && passwordStrength.level < 2) {
    errors.password = '密码强度太弱，请包含大小写字母、数字或特殊字符';
  } else {
    errors.password = '';
  }
};

const validateConfirmPassword = () => {
  if (!formData.confirmPassword) {
    errors.confirmPassword = '请确认密码';
  } else if (formData.confirmPassword !== formData.password) {
    errors.confirmPassword = '两次输入的密码不一致';
  } else {
    errors.confirmPassword = '';
  }
};

const resetForm = () => {
  formData.email = '';
  formData.nickname = '';
  formData.password = '';
  formData.confirmPassword = '';
  loading.value = false;
  showPassword1.value = false;
  showPassword2.value = false;

  // 清除所有错误提示
  Object.keys(errors).forEach((key) => {
    errors[key as keyof FormErrors] = '';
  });

  // 重置密码强度
  passwordStrength.show = false;
  passwordStrength.level = 0;
  passwordStrength.text = '';
  passwordStrength.color = '';
};

const handleClose = () => {
  emit('update:visible', false);
  resetForm();
  isForgotPassword.value = false;
};

const handleOverlayClick = () => {
  handleClose();
};

const switchMode = (mode: boolean) => {
  isLogin.value = mode;
  resetForm();
};

const showForgotPassword = () => {
  isForgotPassword.value = true;
  resetForm();
};

const backToLogin = () => {
  isForgotPassword.value = false;
  resetForm();
};

const handleSocialLogin = async (platform: string) => {
  // 实现社交登录逻辑
  console.log('Social login with:', platform);
};

const handleSubmit = async () => {
  if (loading.value) return;

  if (isForgotPassword.value) {
    validateEmail();
    if (errors.email) return;

    try {
      loading.value = true;
      await sendResetPasswordEmail(formData.email);
      Message.info('重置密码链接已发送到您的邮箱，请查收');
      backToLogin();
    } catch (error) {
      console.error('Error:', error);
    } finally {
      loading.value = false;
    }
    return;
  }

  // 验证所有字段
  validateEmail();
  if (!isLogin.value) {
    validateNickname();
    validatePassword();
    validateConfirmPassword();
  } else {
    validatePassword();
  }

  // 检查是否有错误
  const hasErrors = Object.values(errors).some(error => error !== '');
  if (hasErrors) return;

  try {
    loading.value = true;
    if(isLogin.value) {
      await userStore.login(formData);
    } else {
      await userStore.register(formData);
    }
    handleClose();
  } finally {
    loading.value = false;
  }
};
</script>
<style lang="less" scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
  }

  .close-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border: none;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    transition: all 0.2s;

    &:hover {
      background: #f1f5f9;
      color: #1f2937;
    }
  }
}

.modal-body {
  padding: 24px;
  box-sizing: border-box;
  width: 100%;
}

.auth-tabs {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e2e8f0;

  .tab-btn {
    padding: 8px 0;
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    color: #64748b;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;

    &.active {
      color: #3b82f6;
      border-bottom-color: #3b82f6;
    }

    &:hover:not(.active) {
      color: #1f2937;
    }
  }
}

.login-form {
  width: 100%;
  box-sizing: border-box;

  .form-item {
    margin-bottom: 24px;
    width: 100%;
    box-sizing: border-box;
    position: relative;

    .password-input-wrapper {
      position: relative;
      width: 100%;

      input {
        padding-right: 150px; // 为按钮和强度指示器留出空间
      }

      // 移除浏览器默认的密码切换按钮
      input[type="password"]::-ms-reveal,
      input[type="password"]::-ms-clear {
        display: none;
      }

      input[type="password"]::-webkit-credentials-auto-fill-button,
      input[type="password"]::-webkit-contacts-auto-fill-button {
        display: none !important;
      }
    }

    input {
      width: 100%;
      box-sizing: border-box;
      height: 40px;
      padding: 0 16px;
      border: 1px solid #e2e8f0;
      border-radius: 8px;
      font-size: 14px;
      transition: all 0.2s;

      &:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
      }

      &.error {
        border-color: #ef4444;

        &:focus {
          box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
        }
      }
    }
  }
}
.error-message {
  position: absolute;
  left: 0;
  bottom: -20px;
  font-size: 12px;
  color: #ef4444;
  display: flex;
  align-items: center;
  gap: 4px;
  opacity: 0;
  transform: translateY(-5px);
  animation: slideIn 0.3s ease forwards;

  i {
    font-size: 14px;
  }
}

.form-tips {
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;

  p {
    margin: 0;
    font-size: 13px;
    color: #64748b;
  }
}

.submit-btn {
  width: 100%;
  height: 40px;
  margin-top: 24px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;

  &:hover:not(:disabled) {
    background: #2563eb;
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.forgot-password {
  text-align: right;
  margin-top: -8px;
  margin-bottom: 16px;
}

.back-to-login {
  text-align: center;
  margin-top: 16px;
}

.text-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  font-size: 13px;
  color: #3b82f6;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    color: #2563eb;
    text-decoration: underline;
  }
}

// 自定义密码显示/隐藏按钮样式
.toggle-password {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  padding: 4px 8px;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    color: #1f2937;
  }

  i {
    font-size: 16px;
  }
}

.password-strength {
  position: absolute;
  right: 48px; // 调整位置，为显示/隐藏按钮留出空间
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  gap: 6px;
  pointer-events: none;

  .strength-bars {
    display: flex;
    gap: 2px;

    .bar {
      width: 12px;
      height: 3px;
      background: #e2e8f0;
      border-radius: 1.5px;
      transition: all 0.3s ease;

      &.active {
        background: var(--strength-color);
      }
    }
  }

  .strength-text {
    font-size: 12px;
    min-width: 20px;
    transition: color 0.3s ease;
  }
}

.social-login {
  margin-top: 24px;

  .divider {
    position: relative;
    text-align: center;
    margin: 24px 0;

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 0;
      right: 0;
      height: 1px;
      background: #e2e8f0;
    }

    span {
      position: relative;
      background: #ffffff;
      padding: 0 12px;
      color: #64748b;
      font-size: 13px;
    }
  }

  .social-buttons {
    display: flex;
    justify-content: center;
    gap: 16px;

    .social-btn {
      width: 40px;
      height: 40px;
      border: none;
      border-radius: 50%;
      background: #f1f5f9;
      color: #64748b;
      font-size: 20px;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        transform: translateY(-2px);
      }

      &.qq:hover {
        background: #12B7F5;
        color: white;
      }

      &.wechat:hover {
        background: #07C160;
        color: white;
      }

      &.gitee:hover {
        background: #C71D23;
        color: white;
      }
    }
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  .modal-content {
    background: #1f2937;

    .modal-header {
      border-bottom-color: #374151;

      h3 {
        color: #e5e7eb;
      }

      .close-btn {
        color: #9ca3af;

        &:hover {
          background: #374151;
          color: #e5e7eb;
        }
      }
    }
  }

  .auth-tabs {
    border-bottom-color: #374151;

    .tab-btn {
      color: #9ca3af;

      &.active {
        color: #60a5fa;
        border-bottom-color: #60a5fa;
      }

      &:hover:not(.active) {
        color: #e5e7eb;
      }
    }
  }

  .social-login {
    .divider {
      &::before {
        background: #374151;
      }

      span {
        background: #1f2937;
        color: #9ca3af;
      }
    }

    .social-buttons .social-btn {
      background: #374151;
      color: #9ca3af;

      &:hover {
        background: #4b5563;
      }
    }
  }

  .form-tips {
    background: #374151;

    p {
      color: #9ca3af;
    }
  }

  .text-btn {
    color: #60a5fa;

    &:hover {
      color: #93c5fd;
    }
  }

  .toggle-password {
    color: #9ca3af;

    &:hover {
      color: #e5e7eb;
    }
  }

  input {
    background: #374151 !important;
    border-color: #4b5563 !important;
    color: #e5e7eb !important;

    &::placeholder {
      color: #9ca3af !important;
    }

    &:focus {
      border-color: #60a5fa !important;
      box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1) !important;
    }
  }

  .password-strength {
    .strength-bars .bar {
      background: #4b5563;
    }
  }

  .error-message {
    color: #f87171;
  }

  input.error {
    border-color: #f87171 !important;

    &:focus {
      box-shadow: 0 0 0 3px rgba(248, 113, 113, 0.1) !important;
    }
  }
}

// 动画
@keyframes slideIn {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
